#include <QDebug>

#include "cvlogindialog.h"
#include "mainwindow.h"
#include "ui_cvlogindialog.h"
#include "bizlogic/cvnetworkmanager.h"
#include "bizlogic/cvusermanager.h"
#include "model/cvnetwork.h"
#include "util/cvsettings.h"

CVLoginDialog::CVLoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CVLoginDialog)
{
    ui->setupUi(this);

    /*ui->cbNetwork->addItem("demo.cvtest.com");
    ui->cbNetwork->addItem("eco1-n2.cvtest.com");
    ui->cbNetwork->addItem("broadvision.clearvale.com");
    */

    CVSettings *settings = CVSettings::get();
    QList<Account *> *accounts = settings->getAccounts();
    int accountCount = accounts->size();
    if (accountCount > 0)
    {
        for(int i = 0; i < accountCount; ++i)
        {
            ui->cbNetwork->addItem(accounts->at(i)->getNetwork());
            if (i == 0)
            {
                ui->leEmail->setText(accounts->at(i)->getUserId());
                ui->lePassword->setText(accounts->at(i)->getPassword());
            }
        }
    }

    loading = new QMovie(":/images/loader");

    this->setObjectName("loginDlg");
}

CVLoginDialog::~CVLoginDialog()
{
    delete ui;
}

void CVLoginDialog::validateNetwork(QFocusEvent *e)
{
    if (!ui->cbNetwork->currentText().isEmpty())
    {
        //qDebug() << "==Start validate network==";
        //ui->cbNetwork->setItemIcon(0, QIcon(":/images/loader"));
        //loading->start();
//        CVNetworkManager *manager = CVNetworkManager::get();
//        manager->validateNetwork(ui->cbNetwork->currentText());
//        connect(manager, SIGNAL(validated(bool)), this, SLOT(validatedNetwork(bool)));
    }
}

void CVLoginDialog::validatedNetwork(bool result)
{
    //loading->stop();
    if (result)
    {
        ui->cbNetwork->setStyleSheet("QComboBox {color: black;}");
    }
    else
    {
        ui->cbNetwork->setStyleSheet("QComboBox {color: red;}");
    }
}

void CVLoginDialog::loginAction()
{
    qDebug() << "Login action ...";
    ui->loginBtn->setEnabled(false);
    CVUserManager *manager = new CVUserManager();
    manager->validating(ui->leEmail->text(), ui->lePassword->text(), ui->cbNetwork->currentText());
    connect(manager, SIGNAL(validated(bool,QString,QNetworkReply::NetworkError)), this, SLOT(validateLoginAction(bool,QString,QNetworkReply::NetworkError)));
}

void CVLoginDialog::handleUserSlot(CVUser *user, const QString &msg)
{
    if (user != NULL)
    {
        CVSession *session = CVSession::get();
        session->setUser(user);

        CVSettings *settings = CVSettings::get();
        settings->addAccount(session->getCurrentNetwork()->getUrl(),
                             session->getUserId(),
                             session->getPassword());
    }
    else
    {
        qDebug() << "[CVLoginDialog::handleUserSlot] Error: " << msg;
    }

    ui->loginBtn->setEnabled(true);
    this->hide();

    MainWindow *mainWindow = new MainWindow();
    mainWindow->showMaximized();
    //mainWindow->show();
}

void CVLoginDialog::validateLoginAction(bool result, const QString &msg, QNetworkReply::NetworkError error)
{
    if (result && !msg.isEmpty() && error == QNetworkReply::NoError)
    {
        qDebug() << "Login successfully";
        CVSession *session = CVSession::get();
        session->setSessionId(msg);
        CVNetwork *network = new CVNetwork();
        qDebug() << "[CVLoginDialog] current network: " << ui->cbNetwork->currentText() ;
        network->setUrl(ui->cbNetwork->currentText());
        network->setUserId(ui->leEmail->text());
        network->setPassword(ui->lePassword->text());
        session->setUserId(ui->leEmail->text());
        session->setPassword(ui->lePassword->text());
        session->setCurrentNetwork(network);

        // retrieves user data
        CVUserManager *manager = new CVUserManager();
        manager->getLoggedUser();
        connect(manager, SIGNAL(handleUser(CVUser*,QString)), this, SLOT(handleUserSlot(CVUser*,QString)));
    }
    else
    {
        ui->loginBtn->setEnabled(true);
        if (error == QNetworkReply::NoError)
        {
            qDebug() << msg;
        }
        else
        {
            qDebug() << "network error: " << error;
        }
    }
}
